package com.crmweb.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.crmweb.entity.DTree;
import com.crmweb.dto.TreeModules;
import com.crmweb.entity.Modules;
import com.crmweb.entity.Result;
import com.crmweb.entity.Rolemodules;
import com.crmweb.service.ModulesService;

@RestController
public class ModulesControl {

	@Autowired
	private ModulesService service;
	/**
	 * 以树的形式显示
	 * @return
	 */
	@RequestMapping("syss/getTreeModules")
	public Object getTreeM() {
		/*
		 * List<TreeModules> nodes=service.selTreeMByOrderWeight(); List<TreeModules>
		 * list=service.queryTreeByTM(nodes); return list;
		 */
		List<DTree> list=service.selModulesByWeight();
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("code", 0);
		map.put("msg", "操作成功");
		map.put("data", list);
		return map;
	}
    /**
     * 添加模块
     */
	@RequestMapping("syss/insertModule")
	public Object addModule(Modules modules) {
		Modules moduless=service.checkMNameCF(modules.getName(), modules.getParentId());
		//System.out.println(modules);
		if(moduless==null) {
		int i=service.addModules(modules);
		if(i>0) {
			Result r=new Result("添加模块成功","",true);
			return r;
		}else {
			Result r=new Result("添加模块失败","",false);
			return r;
		}
	  }
		Result r=new Result("添加模块失败,该模块名已存在","",false);
		return r;
	}
	/**
	 * 修改模块
	 */
	@RequestMapping("syss/updatetModule")
	public Object updateM(Modules modules) {
		Modules moduless=service.checkMNameCF(modules.getName(), modules.getParentId());
		//System.out.println(modules);
		if(moduless==null) {
		int i=service.updateModules(modules);
		if(i>0) {
			Result r=new Result("修改模块成功","",true);
			return r;
		}else {
			Result r=new Result("修改模块失败","",false);
			return r;
		}
	  }
		Result r=new Result("修改模块失败,该模块名已存在","",false);
		return r;
	}
	/**
	 * 判断要删除的模块是否有关联
	 */
	@RequestMapping("syss/delModule")
	public Object checkMo(int moduleId) {
		List<Rolemodules> list=service.selMidIsCanDel(moduleId);
		if(list.size()<=0) {
			int i=service.delModules(moduleId);
			if(i>0) {
				Result r=new Result("删除模块成功","",true);
				return r;
			}else{
				Result r=new Result("删除模块失败","",false);
				return r;
			}
			
		}else{
			Result r=new Result("修改模块与角色有关联，不能删除","",false);
			return r;
		}
	}
	/**
	 * 验证同一个父节点下名称是否相同
	 */
	@RequestMapping("syss/checkModulesName")
	public Object yzMname(String name,int parentId) {
		Modules modules=service.checkMNameCF(name, parentId);
		//System.out.println(modules);
		if(modules==null) {
			Result r=new Result("输入正确","",true);
			return r;
		}else {
			Result r=new Result("同一节点下模块名称是否相同","",false);
			return r;
		}
	}
	
}
